/*
 * speex.c
 *
 *  Created on: 28th Dec 2010
 *      Author: bob
 */

#include "codec.h"

// PUBLIC

int lib_speex_init() {

    int quality = 10;
    int rate = 32000;
    int err;

    // Setup for coding
    enc_state = NULL;
    speex_bits_init(&bits);
    enc_state = speex_encoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB));
    speex_encoder_ctl(enc_state, SPEEX_SET_QUALITY, &quality);
    speex_encoder_ctl(enc_state, SPEEX_SET_SAMPLING_RATE, &rate);
    // Set up a resampler to resample to 32K which is the highest sampling rate for speex
    resampler = speex_resampler_init(2, 48000, 32000, quality, &err);

    return 0;
}

int lib_speex_term() {

    // Free everything
    if(enc_state == NULL) return -100;
    speex_bits_destroy(&bits);
    speex_encoder_destroy(enc_state);
    if(byte_ptr != NULL) free(byte_ptr);
    return 0;
}

int lib_speex_get_frame_sz() {

    // Get the expected frame size
    int sz;
    if(enc_state == NULL) return -100;
    speex_encoder_ctl(enc_state, SPEEX_GET_FRAME_SIZE, &sz);
    return sz;
}

int lib_speex_resample(short* in, unsigned int* in_length, short* out, unsigned int* out_length) {

    // Resample the input frame to 32KHz
    if(enc_state == NULL) return -100;
    return speex_resampler_process_interleaved_int(resampler, in, in_length, out, out_length);
}

int lib_speex_encode(short *samples, char*encoded_bytes) {

    // Encode the data
    int bytes_written;

    if(enc_state == NULL) return -100;
    speex_bits_reset(&bits);
    speex_encode_stereo_int(samples, 640, &bits);
    speex_encode_int(enc_state, samples, &bits);
    bytes_written = speex_bits_write(&bits, encoded_bytes, 640);

    return bytes_written;
}
